<template>
  <div id="root">
  <div class="todo-container">
    <div class="todo-wrap">
      <my-header :review="review"/>
      <list :todoList="todoList" :checkTodo='checkTodo' :deteleTodo='deteleTodo'/>
     <my-footer  :todoList="todoList" :clearAlltodo="clearAlltodo"/>
    </div>
  </div>
</div>
</template>
<script>
import MyHeader from './views/MyHeader'
import List from './views/List'
import MyFooter from './views/MyFooter'
export default {
  components: {
    MyHeader,
    List,
    MyFooter
  },
  data () {
    return {
      todoList: JSON.stringify(localStorage.getItem('todoList')) || []
    }
  },
  methods: {
    // 添加一个项目
    review (x) {
      // console.log('我收到了子组件给我传的值', x)
      this.todoList.unshift(x)
    },
    // 勾选或者取消
    checkTodo (id) {
      // 拿到被改的id。找到相同的
      this.todoList.forEach(val => {
        if (val.id === id) val.done = !val.done
      })
    },
    // 删除一个项目
    deteleTodo (id) {
      this.todoList = this.todoList.filter(val => {
        // 过过滤到不要的，把要的在放回原来的数组，渲染页面
        return val.id === !id
      })
    },
    // 清除被选中的所有项
    clearAlltodo () {
      this.todoList = this.todoList.filter((todo) => {
        // 返回所有为真的值，done 为真的不要
        return !todo.done
      })
    }
  },
  watch: {
    // 监视数据，setItem 进行数据的缓存和及时的更新 JSON.stringify()是让数据变成键值对形式的字符串
    todoList: {
      deep: true,
      handler (value) { localStorage.setItem('todoList', JSON.stringify(value)) }

    }
  }
}
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

</style>
